package jian.hamster.controller
{
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import jian.hamster.event.GameEvent;

	public class TimerController extends EventDispatcher
	{
		private static var _instance:TimerController;
		private var _timer:Timer;
		private var _callBacks:Dictionary;
		public static function get instance():TimerController
		{
			return !_instance ? (_instance=new TimerController()) : _instance;
		}
		
		public function TimerController()
		{
			if(!_instance)
			{
				_callBacks = new Dictionary();
				
				_timer = new Timer(1);
				_timer.addEventListener(TimerEvent.TIMER, __onTimerTick);
				_timer.start();
			}
		}
		
		protected function __onTimerTick(event:TimerEvent):void
		{
			if(_instance)
			{
				_instance.dispatchEvent(new GameEvent(GameEvent.ENTER_FRAME));
			}
			if(_callBacks)
			{
				for (var cb:Function in  _callBacks)
				{
					if(getTimer() - _callBacks[cb][1] >=_callBacks[cb][0])
					{
//						trace(getTimer() - _callBacks[cb][1], _callBacks[cb][0])
						_callBacks[cb][1] = getTimer(); 
						cb.call();
						if(_callBacks[cb][2] != -1 && (_callBacks[cb][1] - _callBacks[cb][0] >= _callBacks[cb][2]))
						{
							deleteTickerCallBack(cb);
						}
					}
				}
			}
		}
		
		/**
		 * 新增一个计时器的回调<br> 
		 * @param $interval 每隔多少秒回调
		 * @param $callBack 回调的具体函数
		 * @param $finish 多少毫秒之后自动结束(-1表示永不结束)
		 * 
		 */		
		public function addTickerCallBack($interval:Number, $callBack:Function, $finish:int=-1):void
		{
			if(!_callBacks.hasOwnProperty($callBack))
			{
				_callBacks[$callBack] = [$interval,getTimer(),$finish];
			}
			else
			{
				trace("重复添加回调！");
			}
		}
		
		public function deleteTickerCallBack($callBack:Function):void
		{
			if(_callBacks[$callBack])
			{
				delete _callBacks[$callBack];
			}
		}
	}
}